#pragma once
#include "Socket.hpp"
#include "log.hpp"
#include <signal.h>
#include <functional>

extern Log lg;

using func_t = std::function<std::string(std::string &package)>;

class Tcpserver
{
public:
    Tcpserver(uint16_t port, func_t callback)
        : callback_(callback), port_(port)
    {
    }

    bool InitServer()
    {
        listen_sock_.Socket();
        listen_sock_.Bind(port_);
        listen_sock_.Listen();
        lg(Info, "InitServer success!!!!");
        return true;
    }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd_ = listen_sock_.Accept(clientip, clientport);
            if (sockfd_ == -1)
            {
                lg(Warning, "accrpt error,%d:%s", errno, strerror(errno));
                continue;
            }
            lg(Info, "accept a new link,sockfd: %d,clientip:%s ,clientport: %d", sockfd_, clientip, clientport);

            // 提供服务
            if (fork() == 0)
            {
                // 子进程拿着自己的服务套接字，关闭父进程的
                listen_sock_.Close();
                std::string inbuffer_stream;
                while (true)
                {
                    char buffer[128];
                    int n = read(sockfd_, buffer, sizeof(buffer) - 1);
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        inbuffer_stream += buffer;
                        lg(Debug, "debug:\n %s", inbuffer_stream.c_str());
                        
                        //服务端如果一次收到多个报文，应该将报文一起解析后返回
                        while (true)
                        {
                            std::string info = callback_(inbuffer_stream);
                            if (info == "")
                                break;
                            lg(Debug,"debug,response:\n%s",info.c_str());
                            lg(Debug,"debug:\n %s", inbuffer_stream.c_str());
                            write(sockfd_, info.c_str(), info.size());
                        }
                    }
                    else
                        break;
                }
                exit(0);
            }

            // 父进程关闭子进程的套接字
            close(sockfd_);
        }
    }

    ~Tcpserver()
    {
    }

private:
    Sock listen_sock_;
    uint16_t port_;
    func_t callback_;
};